# -*- encoding: utf-8 -*-
'''
@File    :   aqwd.py
@Time    :   2020/03/12 12:32:52
@Author  :   YChienHung
@Version :   1.0
@Contact :   1399449399@qq.com
@License :   Copyright (C) 2019 YChienHung
@Desc    :   None
'''

# here put the import lib
import requests
# import json
import re


############################
account = "15726508385"
password = "tenglong_0418"
url_login = "http://exam.sdsafeschool.gov.cn/m_login.php?adminaction=login"
url_spider = "http://exam.sdsafeschool.gov.cn/m_mokao.php"
url_answer = ""
############################


d = {}


class SafeSystem(object):
    def __init__(self, account, password):
        super(SafeSystem, self).__init__()
        self.account = account
        self.password = password
        self.state_login = False
        self.session = self.login()

    HEADERS = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36",
        "Referer": "http://exam.sdsafeschool.gov.cn/m_login.php",
        "accept-encoding": "gzip, deflate",
        "accept-language": "zh-CN,zh;q=0.9",
    }

    def login(self):
        params = {
            "sch_id": 205,  # 197 是山科大
            "shouji": self.account,
            "pppp": self.password
        }
        session = requests.Session()
        req = session.post(url_login, params=params,
                           timeout=5, headers=self.HEADERS)
        if '欢迎' in req.text:
            self.state_login = True
        return session

    def spider(self):
        if self.state_login is False:
            print("尚未登录成功")
            return
        # with open("安全问答自动答题系统\data.txt", "w") as f:
        #     f.write(text)
        #     f.close()
        # <span class="title">序号&nbsp;戴口罩一定要带n95（  ）</span><br><br>
        pat1 = "<span class=\"title\">{}&nbsp;{}</span>".format(
            "[0-9]{1,2}", "(.*?)")
        pat2 = "<span id=\"daan_{}\">{}</span>".format("[0-9]{1,2}", "(.*?)")
        pattern1 = re.compile(pat1)
        pattern2 = re.compile(pat2)
        while True:
            x = 0
            req = self.session.get(url_spider, headers=self.HEADERS)
            text = req.content.decode().strip().replace("\r\n", "").replace("\n", "")

            answers = pattern2.findall(text)
            questions = pattern1.findall(text)
            for question, answer in zip(questions, answers):
                if d.get(question, -1) is -1:
                    x = x+1
                    d[question] = answer
            print("本次总共添加了{}个答案".format(x))

            if x == 0:
                break


if __name__ == "__main__":
    obj = SafeSystem(account, password)
    for i in range(100):
        obj.spider()
    # print("本次获取的内容长度为：", len(d))
    if len(d) != 304:
        print("信息抓取异常", len(d))

    s = str(d)
    s = s.replace("{", "").replace("}", "").replace(",", "\n").strip()
    with open("安全问答自动答题系统\\data.json", "w") as f:
        f.write(s)
        f.close()
